import {ref} from 'vue'
import {defineStore} from 'pinia'
import {notificationMess} from '@/utils/message'
import {cloudGeneralObject} from '@/uniCloud-alipay'
import router from '@/router'
import {USER_INFO} from '@/common/data/keys'
import {defaultUserInfo} from '@/store/user/config'

//定义用户store
const useUserStore = defineStore('user', () => {
  //用户信息
  const userInfo = ref(defaultUserInfo)

  //检查用户账号的方法
  const fetchCheckUserAction = async (account) => (await cloudGeneralObject.getListByField('admin-user', 'account', account)).data

  //登录逻辑
  const fetchLoginAction = async ({account, password}) => {
    //查询是否有此账号
    const data = (await fetchCheckUserAction(account))[0]
    if (!data) return notificationMess.error('账号不存在')

    //判断密码是否正确
    if (password !== data.password) return notificationMess.error('密码错误')

    //登录成功则保存用户数据
    userInfo.value = data
    uni.setStorageSync(USER_INFO, data)

    //跳转界面
    router.replace('/main')
  }

  //退出登录逻辑
  const fetchLogoutAction = async () => {
    //移除用户信息
    userInfo.value = defaultUserInfo
    uni.removeStorageSync(USER_INFO)

    //退出到欢迎界面
    router.replace('/login')
  }

  return {userInfo, fetchLoginAction, fetchLogoutAction}
})


export default useUserStore
